package com.ruoyi.auth.service;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.BaseException;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.internet.api.RemoteIntUserService;
import com.ruoyi.internet.api.domain.IntUser;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author: cjie
 * @description: 产业互联网用户登录
 * @date: 2021/8/16
 */
@Component
public class InternetUserLoginService {
    @Resource
    private RemoteIntUserService remoteIntUserService;
    @Resource
    private TokenService tokenService;
    @Resource
    private RedisService redisService;

    public R<?> login(String username, String password) {
        IntUser queryUser = new IntUser();
        queryUser.setUserName(username);
        R<IntUser> r = remoteIntUserService.getUserInfoByUsernameOrPhone(queryUser);
        if (r.getCode() == R.SUCCESS) {
            if (!SecurityUtils.matchesPassword(password, r.getData().getPassword())) {
                throw new BaseException("用户名或密码错误");
            }
            LoginUser loginUser = new LoginUser();
            loginUser.setUserid(r.getData().getId());
            loginUser.setUsername(r.getData().getUserName());
            loginUser.setType(r.getData().getType());
            return R.ok(tokenService.createToken(loginUser));
        } else {
            throw new BaseException("登录用户：" + username + " 不存在");
        }
    }

    public R<?> phoneLogin(String phone, String code) {
        IntUser queryUser = new IntUser();
        queryUser.setPhone(phone);
        R<IntUser> r = remoteIntUserService.getUserInfoByUsernameOrPhone(queryUser);
        if (r.getCode() == R.SUCCESS) {
            String checkCode = redisService.getCacheObject(phone);
            if(StringUtils.isEmpty(code)){
                return R.fail("验证码不存在或已过期");
            }
            if(!checkCode.equals(code)){
                return R.fail("验证码不正确");
            }

            LoginUser loginUser = new LoginUser();
            loginUser.setUserid(r.getData().getId());
            loginUser.setUsername(r.getData().getUserName());
            return R.ok(tokenService.createToken(loginUser));
        } else {
            throw new BaseException("登录用户：" + phone + " 不存在");
        }
    }
}
